package models

import (
	"awesome/config"
	"gorm.io/gorm"
	"log"
)

type Device struct {
	gorm.Model
	Mcid    string `json:"mcid" gorm:"not null; uniqueIndex"`
	GroupId uint   `json:"group_id" gorm:"default: 0"`
}

func CreateUpdateDevice(device *Device) error {
	err := config.DB.Where("Mcid = ?", device.Mcid).Assign(Device{GroupId: device.GroupId}).FirstOrCreate(&device).Error
	if err != nil {
		log.Fatalln(err)
		return err
	}
	return nil
}

func UpdateDevice(device *Device) error {
	return config.DB.Model(&Device{}).Where("Mcid = ?", &device.Mcid).Update("group_id", &device.GroupId).Error
}

func GetDeviceList(sizeInt int, offset int) (*[]Device, error) {
	var devices []Device
	err := config.DB.Model(&Device{}).Limit(sizeInt).Offset(offset).Find(&devices).Error
	if err != nil {
		return nil, err
	}
	return &devices, nil
}

func DeleteDevice(device *Device) error {
	return config.DB.Where("Mcid = ?", &device.Mcid).Delete(&Device{}).Error
}

func GetDeviceByID(id uint) (*Device, error) {
	var device Device
	err := config.DB.First(&device, id).Error
	if err != nil {
		return nil, err
	}
	return &device, nil
}
